import React, { useState, useEffect, useRef } from 'react'
import './index.scss'
import Title from 'antd/es/typography/Title'
import { Button, Card, DatePicker, Descriptions, Flex, Segmented, Empty, Spin, message, Modal } from 'antd'
import { ExportOutlined } from '@ant-design/icons'
import icon from '@/assets/images/enterprise/icon@2x.png'
import BarChart from '@/components/BarChart'
import { FullscreenExitOutlined, FullscreenOutlined } from "@ant-design/icons"
import WordcloudChart from '@/components/WordcloudChart'
import Zijinliuxiang from '@/components/Zijinliuxiang'
import { transactionAPI, fundflowAPI, exportgenerateAPI } from '@/apis'
import dayjs from 'dayjs'
import { toggleFull } from '@/utils'
import axios from 'axios'
import ReportCreateProgress from '@/components/ReportCreateProgress'
const { RangePicker } = DatePicker
export default function Jiaoyitezheng({ data }) {
    const [isFullScreen, setIsFullScreen] = useState(false);
    const [chartBoxHeight, setChartBoxHeight] = useState(360)
    // const [startDate, setStartDate] = useState(dayjs().startOf('year').format('YYYY-MM-DD'))
    // const [endDate, setEndDate] = useState(dayjs(new Date()).format('YYYY-MM-DD'))
    // const [startDate, setStartDate] = useState('2024-01-01')
    // const [endDate, setEndDate] = useState('2024-12-31')
    const [year, setYear] = useState(String(dayjs().year()))
    const [items, setitems] = useState()
    const [items1, setitems1] = useState()
    const [items2, setitems2] = useState()
    const [items3, setitems3] = useState()
    const [items4, setitems4] = useState()
    const [xAxisData, setxAxisData] = useState([])
    const [statisticsData, setstatisticsData] = useState(null)
    const [isloading, setisloading] = useState(false)
    const [flowTabs, setflowTabs] = useState([])
    const [flowTab, setflowTab] = useState(null)
    const [zjlxdata, setzjlxdata] = useState(null)
    const [flowLoading, setFlowLoading] = useState(false)
    const [messageApi, contextHolder] = message.useMessage();
    const [isModalOpen, setIsModalOpen] = useState(false);
    const handleDate = (time) => {
        // setStartDate(dayjs(time[0]).format('YYYY-MM-DD'))
        // setEndDate(dayjs(time[1]).format('YYYY-MM-DD'))
        if (time) {
            setYear(dayjs(time).format('YYYY'));
        } else {
            setYear(String(dayjs().year()));
        }
    }
    useEffect(() => {
        const handleKeyDown = () => {
            // 全屏
            if (document.fullscreenElement) {
                setIsFullScreen(true);
                setChartBoxHeight('100%')
            } else {
                setIsFullScreen(false);
                setChartBoxHeight(360)
            }
        };
        document.addEventListener('fullscreenchange', handleKeyDown);
    }, [])
    useEffect(() => {
        const iscy = data.company_info[0].IS_CYDW;
        const tabs = iscy === 0 
            ? ['按行业', '按物品', '按归属'] 
            : ['按行业', '按物品', '按实际控制人'];
        setflowTabs(tabs);
        if (tabs.length > 0) {
            handlechangeflowtab(tabs[0]);
        }
    }, [data]);
    useEffect(() => {
        if (flowTabs.length > 0) {
            setflowTab('industry')
        }
    }, [flowTabs])
    const handlechangeflowtab = (value) => {
        let flowkey;
        if (value === '按行业') {
            flowkey = 'industry'
        } else if (value === '按物品') {
            flowkey = 'invoice'
        } else if (value === '按归属') {
            flowkey = 'belonging'
        } else if (value === '按实际控制人') {
            flowkey = 'controller'
        }
        setflowTab(flowkey)
    }
    useEffect(() => {
        function getData() {
            setisloading(true)
            transactionAPI({
                company: data.company_info[0].GSMC,
                companytype: data.company_info[0].IS_CYDW,
                year
            }).then(res => {
                if (!res || !res.data || !res.data.jyzb) {
                    // 数据为空时，将所有 items 设置为空数组
                    setitems([{
                            key: '1',
                            label: '月底交易占比',
                            children: '暂无数据',
                        },
                        {
                            key: '2',
                            label: '月初交易占比',
                            children: '暂无数据',
                        }]);
                    setitems1([{
                            key: '1',
                            label: '年底交易占比',
                            children: '暂无数据',
                        },
                        {
                            key: '2',
                            label: '年初交易占比',
                            children: '暂无数据',
                        },]);
                    setitems2([ {
                            key: '1',
                            label: '上游交易总额',
                            children: '暂无数据',
                        },
                        {
                            key: '2',
                            label: '下游交易总额',
                            children: '暂无数据',
                        },]);
                    setitems3([ {
                            key: '1',
                            label: '上游交易笔数',
                            children: '暂无数据',
                        },
                        {
                            key: '2',
                            label: '下游交易笔数',
                            children: '暂无数据',
                        },]);
                    setitems4([{
                            key: '1',
                            label: '交易最频繁月份',
                            children: '暂无数据',
                        },
                        {
                            key: '2',
                            label: '占全年交易额',
                            children: '暂无数据',
                        },]);
                    setisloading(false);
                    return;
                }
                setitems([
                    {
                        key: '1',
                        label: '月底交易占比',
                        children: <Flex align='baseline'><Title level={4}>{res.data.jyzb?.ym_jy_ratio}</Title></Flex>,
                    },
                    {
                        key: '2',
                        label: '月初交易占比',
                        children: <Flex align='baseline'><Title level={4}>{res.data.jyzb?.yc_jy_ratio}</Title></Flex>,
                    },
                    // {
                    //     key: '3',
                    //     label: '差值',
                    //     children: <Flex align='baseline' className='add'><Title level={4}>{res.data.jyzb.ym_jy_ratio - res.data.jyzb.yc_jy_ratio}</Title>%</Flex>,
                    // }
                ])
                setitems1([
                    {
                        key: '1',
                        label: '年底交易占比',
                        children: <Flex align='baseline'><Title level={4}>{res.data.jyzb?.nm_jy_ratio}</Title></Flex>,
                    },
                    {
                        key: '2',
                        label: '年初交易占比',
                        children: <Flex align='baseline'><Title level={4}>{res.data.jyzb?.nc_jy_ratio}</Title></Flex>,
                    },
                    // {
                    //     key: '3',
                    //     label: '差值',
                    //     children: <Flex align='baseline' className='minus'><Title level={4}>{res.data.jyzb.nm_jy_ratio - res.data.jyzb.nc_jy_ratio}</Title>%</Flex>,
                    // }
                ])
                setitems2([
                    {
                        key: '1',
                        label: '上游交易总额',
                        children: <Flex align='baseline'><Title level={4}>{(res.data.jyzb?.sy_total_amount+'').toLocaleString()}</Title>万</Flex>,
                    },
                    {
                        key: '2',
                        label: '下游交易总额',
                        children: <Flex align='baseline'><Title level={4}>{(res.data.jyzb?.xy_total_amount+'').toLocaleString()}</Title>万</Flex>,
                    },
                    // {
                    //     key: '3',
                    //     label: '差值',
                    //     children: <Flex align='baseline' className='minus'><Title level={4}>{res.data.jyzb.sy_total_amount - res.data.jyzb.xy_total_amount}</Title>万</Flex>,
                    // }
                ])
                setitems3([
                    {
                        key: '1',
                        label: '上游交易笔数',
                        children: <Flex align='baseline'><Title level={4}>{res.data?.jyzb?.sy_total_count}</Title>笔</Flex>,
                    },
                    {
                        key: '2',
                        label: '下游交易笔数',
                        children: <Flex align='baseline'><Title level={4}>{res.data?.jyzb?.xy_total_count}</Title>笔</Flex>,
                    },
                    // {
                    //     key: '3',
                    //     label: '差值',
                    //     children: <Flex align='baseline' ><Title level={4}>{res.data.jyzb.sy_total_amount - res.data.jyzb.xy_total_amount === 0 ? '持平' : res.data.jyzb.sy_total_amount - res.data.jyzb.xy_total_amount}</Title></Flex>,
                    // }
                ])
                setitems4([
                    {
                        key: '1',
                        label: '交易最频繁月份',
                        children: <Flex align='baseline'><Title level={4}>{res.data?.jyzb?.sxy_jy_max_month}</Title>{res.data?.jyzb?.sxy_jy_max_month !== '暂无' && '月'}</Flex>,
                    },
                    {
                        key: '2',
                        label: '占全年交易额',
                        children: <Flex align='baseline'><Title level={4}>{res.data?.jyzb?.max_month_jy_ratio}</Title></Flex>,
                    },
                    // {
                    //     key: '3',
                    //     label: '单笔交易最大额度',
                    //     children: <Flex align='baseline' ><Title level={4}>{res.data.jyzb.max_month_jy_ratio}</Title>万</Flex>,
                    // }
                ])
                // 开始日期作为图表的年份,数据格式{"01":"XXXX"}
                setxAxisData(res.data?.jytj?.sy_jy_list.map((item, index) => year + '-' + (index + 1)))

                let sy_jy_list = []
                let xy_jy_list = []

                //if(res.data.length > 0){
                if(res.data?.jytj){
                     sy_jy_list = res.data?.jytj?.sy_jy_list.map((item, index) => item[ (index+1).toString().padStart(2, '0') ])
                     xy_jy_list = res.data?.jytj?.xy_jy_list.map((item, index) => item[ (index+1).toString().padStart(2, '0') ])
                }

                //console.log("上游交易："+sy_jy_list)
                setstatisticsData({
                    yName: '交易金额(万元)',
                    data: [
                        {
                            name: '上游交易金额',
                            data: [...sy_jy_list]
                        },
                        {
                            name: '下游交易金额',
                            data: [...xy_jy_list]
                        }
                    ]
                })
                setisloading(false)
            })
        }
        getData()
    }, [data, year])
    useEffect(() => {
        if (!flowTab) return;
        function getFlow() {
            setFlowLoading(true)
            fundflowAPI({
                company: data.company_info[0].GSMC,
                companytype: data.company_info[0].IS_CYDW,
                year,
                type: flowTab
            }).then(res => {
                // res.data && setzjlxdata(res.data[0])
                if (res.data && res.data.length > 0) {
                    const firstData = res.data[0];
                    console.log(firstData)
                    // 判断 edges 是否为空数组
                    if (firstData.edges.length === 0) {
                        // 当 edges 为空时，将 shequdata 置为空
                        setzjlxdata(null); // 或者使用空对象 {}
                    } else {
                        // 否则正常设置 shequdata
                        setzjlxdata(firstData);
                    }
                } else {
                    // res.data 不存在或为空数组时，也置空 shequdata
                    setzjlxdata(null);
                }                  
            }).finally(() => {
                setFlowLoading(false)
            })
        }
        getFlow()
    }, [data,year,flowTab])
    const showModal = () => {
        setIsModalOpen(true);
    };
    const handleOk = () => {
        setIsModalOpen(false);
    };
    const handleCancel = () => {
        setIsModalOpen(false);
    };
    const report_download = () => {
        // 生成报告
        exportgenerateAPI({
            company: data.company_info[0].GSMC,
        }).then(res => {
            if (res.code == 200) {
                messageApi.open({
                    type: 'success',
                    content: res.message,
                });
                axios.get(`http://192.168.1.188:9000/kshx/download-reportfile?uuid=${res.data}`, {
                    responseType: 'blob', 
                    headers: {
                        Authorization: 'Bearer ' + localStorage.getItem('kshxtoken')
                    }
                }).then(res => {
                    const blob = new Blob([res.data], { type: res.headers['content-type'] });
                    let fileName = data.company_info[0].GSMC + '.docx'; // 默认名
                    // 创建下载链接并触发下载
                    const url = window.URL.createObjectURL(blob);
                    const a = document.createElement('a');
                    a.href = url;
                    a.download = fileName;
                    document.body.appendChild(a);
                    a.click();
                    a.remove();
                    window.URL.revokeObjectURL(url);
                }).catch(err => {
                    console.error('文件下载失败:', err);
                });
            }else{
                messageApi.open({
                    type: 'error',
                    content: res.message,
                });
            }
        }).catch(()=>{
            messageApi.open({
                type: 'error',
                content: '报告生成失败！',
            });
        })
    }
    return (
        <Spin tip="页面加载中..." spinning={isloading} size='large'>
            <div className='exchange-container'>
                <Flex justify='center' className='title'>
                    <Title level={3}>{data.company_info[0].GSMC}</Title>
                    {contextHolder}
                    <Button className='btn' type='link' icon={<ExportOutlined />} onClick={showModal}>导出报告</Button>
                    <Modal
                        title="生成报告"
                        closable={{ 'aria-label': 'Custom Close Button' }}
                        open={isModalOpen}
                        onOk={handleOk}
                        onCancel={handleCancel}
                        footer={null}
                    >
                        <ReportCreateProgress data={data}/>
                    </Modal>
                </Flex>
                <Flex justify='center' style={{ marginTop: '14px' }}>
                    {/* <RangePicker onChange={handleDate} defaultValue={[dayjs(startDate, 'YYYY-MM-DD'), dayjs(endDate, 'YYYY-MM-DD')]}></RangePicker> */}
                    <DatePicker onChange={handleDate} defaultValue={dayjs(year, 'YYYY')} picker="year" />
                </Flex>
                <Card className='indicator-wrap'>
                    <Flex>
                        <Flex align='center'>
                            <img src={icon} style={{ width: '22px', marginRight: '8px' }} alt='' />
                            <Title level={5}>交易指标</Title>
                        </Flex>
                    </Flex>
                    <Flex className='desc-wrap'>
                        <Descriptions colon={false} column={1} layout="vertical" items={items} />
                        <Descriptions colon={false} column={1} layout="vertical" items={items1} />
                        <Descriptions colon={false} column={1} layout="vertical" items={items2} />
                        <Descriptions colon={false} column={1} layout="vertical" items={items3} />
                        <Descriptions colon={false} column={1} layout="vertical" items={items4} />
                    </Flex>
                </Card>
                <Flex vertical gap={16}>
                    <Flex style={{ marginTop: '24px' }} justify='space-between'>
                        <Title level={5}>资金流向</Title>
                        <Segmented
                            options={flowTabs}
                            onChange={handlechangeflowtab}
                        />
                    </Flex>
                    <Spin spinning={flowLoading}>
                        <div className="tags-container tags-container2" >
                            <Flex className="title" justify="space-between" align="center">
                                <p>{data.company_info[0].GSMC}</p>
                                <Button onClick={() => toggleFull('.tags-container2')} size="small" color="primary"
                                    variant="text" icon={isFullScreen ? <FullscreenExitOutlined /> : <FullscreenOutlined />}>{isFullScreen ? '退出全屏' : '全屏查看'}</Button>
                            </Flex>
                            <Flex vertical justify="center" className="chart-box" style={{ width: '100%', height: chartBoxHeight }}>
                                {zjlxdata && <Zijinliuxiang data={zjlxdata} />}
                                {!zjlxdata && <Empty description='暂无数据' image={Empty.PRESENTED_IMAGE_SIMPLE}></Empty>}
                            </Flex>  
                        </div>
                    </Spin>
                </Flex>
                <Flex style={{ marginTop: '24px' }} justify='space-between'>
                    <Title level={5}>交易统计</Title>
                    {/* <Segmented
                    options={['每周', '每月', '每年']}
                    onChange={(value) => {
                        console.log(value); // string
                    }}
                /> */}
                </Flex>
                <Flex vertical justify="center" className="chart-box" style={{ width: '100%', height: 360, marginTop: 20 }}>
                    {statisticsData && <BarChart xAxisData={xAxisData} data={statisticsData} />}
                    {!statisticsData && !isloading && <Empty description='暂无数据' image={Empty.PRESENTED_IMAGE_SIMPLE}></Empty>}
                </Flex>
            </div>
        </Spin>
    )
}
